package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.mapper.*;
import com.sky.service.OrederService;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class OrederServiceImpl implements OrederService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 提价订单
     *
     * @param dto
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        // 构建orders对象
        Orders orders = new Orders();
        // 搬运数据
        BeanUtils.copyProperties(dto, orders);

        // 补充数据
        orders.setNumber(UUID.randomUUID().toString().replace("-", ""));  // 订单号

        orders.setStatus(1); // 订单状态
        // 根据用户id查询用户信息
        User user = userMapper.findByUid(BaseContext.getCurrentId());
        orders.setUserName(user.getName()); // 下单用户名

        orders.setUserId(BaseContext.getCurrentId()); // 下单用户id

        orders.setOrderTime(LocalDateTime.now()); // 下单时间

        orders.setPayStatus(0); // 支付状态

        AddressBook address = addressBookMapper.getById(orders.getAddressBookId());
        orders.setPhone(address.getPhone()); // 收货电话

        String addressname = address.getProvinceName() + address.getCityName() + address.getDistrictName() + address.getDetail();
        orders.setAddress(addressname); // 收货地址

        orders.setConsignee(address.getConsignee()); // 收货人名字
        // 添加到订单表
        orderMapper.add(orders);

        // 添加到订单详情表


        //先获取当前用户的购物车信息
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.findByUid(BaseContext.getCurrentId());

        // 组装订单详情表对象
        List<OrderDetail>  orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            // 遍历一次,就创建一个订单 详情对象
            OrderDetail detail = new OrderDetail();

            // 补数据
            BeanUtils.copyProperties(cart, detail);
            detail.setOrderId(orders.getId());

            orderDetailList.add(detail);
        }

        // 批量添加到订单详情表
        orderDetailMapper.add(orderDetailList);

        // 清空购物车
        shoppingCartMapper.clean(BaseContext.getCurrentId());

        // 构建返回结果
        return OrderSubmitVO.builder().id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount()).build();
    }
}
